<script setup>
import { ref, onMounted, computed, unref, nextTick } from 'vue'
import { queryAddress, queryAddressLink, getCommonDictByType, getByDictType } from '@/api/common'
import { message } from 'ant-design-vue'
import { DraggableModal } from '@/components/core/draggable-modal'
import { addContack, modifyContack } from '@/api/comprehensive'
const props = defineProps({
  phoneEditInfo: {
    type: Object,
    required: true
  },
  showSearchPageLink: {
    // 弹框是否展示返回综合查询link
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['updateVisible'])

const fieldNames = { label: 'dictName', value: 'dictCode' }
const flagList = [
  { dictName: '是', dictCode: '01', dictEName: '是', dictSort: 1 },
  { dictName: '否', dictCode: '02', dictEName: '否', dictSort: 2 }
]
const isUpdate = computed(() => {
  return props.phoneEditInfo.type === 'update'
})

const rules = {
  relationshipWithInsured: [{ required: true, message: '请选择与被保人关系', trigger: 'change' }],
  contactCountry: [{ required: true, message: '请选择国家', trigger: 'change' }],
  contactProvince: [{ required: true, message: '请选择省份', trigger: 'change' }],
  contactCity: [{ required: true, message: '请选择城市', trigger: 'change' }],
  officeTel: [
    { pattern: /^([0-9-]+)$/, message: '办公电话只允许录入数字和 - ', trigger: 'change' }
  ],
  homeTel: [{ pattern: /^([0-9-]+)$/, message: '家庭电话只允许录入数字和 - ', trigger: 'change' }],
  fax: [{ pattern: /^([0-9-]+)$/, message: '传真号码只允许录入数字和 - ', trigger: 'change' }],
  contactAddress: [{ pattern: /^[^'‘]*$/, message: '详细地址不能包含单引号', trigger: 'blur' }]
}
let formState = ref({
  relationshipWithInsured: null,
  contactNameEn: '',
  contactNameCn: '',
  company: '', // 公司
  department: '', // 部门
  position: null, //职位
  contactCountry: null, //国家
  contactProvince: null, //省份
  contactCity: null, //城市
  contactAddress: '', //详细地址
  addRemark: '', //地址备注
  zipcode: '', //邮编
  officeTel: '', //办公电话
  homeTel: '', //家庭电话
  fax: '', // 传真
  mobile: '', //手机号码
  interCode: '', // 区号
  msgFlag: null //是否愿意接受短信
})
async function initData() {
  formState.value = {
    ...formState.value,
    ...props.phoneEditInfo
  }
  getProfessionList()
  getReleationshipList()
  await getCountryList()
  await getProvinceList('init')
  await getCityList('init')
}
// 获取职业列表
const professionList = ref([])
async function getProfessionList() {
  let res = await getCommonDictByType({ dictType: 'position' })
  if (res.isSuccess) {
    const list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    professionList.value = list
  }
}
// 获取与被保人关系列表
const relationshipList = ref([])
async function getReleationshipList() {
  let res = await getByDictType({ dictType: 'relation' })
  if (res.isSuccess) {
    const list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    relationshipList.value = list
  }
}

// 获取省市区列表
const countryList = ref([])
async function getCountryList() {
  const param = {
    addressType: '02'
  }
  let res = await queryAddressLink(param)
  if (res && res.isSuccess) {
    const list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          dictCode: v.addressCode,
          dictName: v.addressEnName
        })
      })
    countryList.value = list
  }
}
const provinceList = ref([])
async function getProvinceList(type) {
  const formData = unref(formState)
  const param = { addressType: '03', upCode: formData.contactCountry }
  let res = null
  if (type == 'init') {
    res = await queryAddress(param)
  } else {
    if (!formData.contactCountry) return
    res = await queryAddressLink(param)
  }
  if (res && res.isSuccess) {
    let list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          dictCode: v.addressCode,
          dictName: v.addressEnName
        })
      })
    provinceList.value = list
  }
}
const cityList = ref([])
async function getCityList(type) {
  const formData = unref(formState)
  const param = { addressType: '04', upCode: formData.contactProvince }
  let res = null
  if (type == 'init') {
    res = await queryAddress(param)
  } else {
    if (!formData.contactProvince) return
    res = await queryAddressLink(param)
  }
  if (res && res.isSuccess) {
    let list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          dictCode: v.addressCode,
          dictName: v.addressEnName
        })
      })
    cityList.value = list
  }
}
// 切换国家
function handleCountryChange() {
  formState.value.contactProvince = null
  formState.value.contactCity = null
  provinceList.value = []
  cityList.value = []
  getProvinceList('change')
}
// 切换省份
function handleProvinceChange() {
  formState.value.contactCity = null
  cityList.value = []
  getCityList('change')
}

const phoneEditVisible = ref(false)
onMounted(async () => {
  await nextTick()
  phoneEditVisible.value = true
  initData()
})
const formRef = ref()
const loading = ref(false)
function checkSumbit() {
  const { mobile, interCode, msgFlag } = unref(formState)
  if (msgFlag == '01') {
    if (!mobile) {
      return { code: 'err', msg: '是否愿意接受短信为是时，手机号为必录项' }
    }
    const isChinaMobile = /^1[3-9]\d{9}$/.test(mobile)
    if (interCode != '86') {
      if (mobile && isChinaMobile) {
        return { code: 'err', msg: '中国大陆手机号码,区号必须是86' }
      } else {
        return { code: 'err', msg: '手机号不符合中国大陆手机号码时，是否愿意接受短信只能为否' }
      }
    }
  }
  return { code: 'ok' }
}
function confirmSave() {
  const validateRed = checkSumbit()
  if (validateRed.code == 'err') {
    message.error(validateRed.msg)
    return
  }
  formRef.value
    .validate()
    .then(async () => {
      loading.value = true
      const param = {
        ...formState.value
      }
      let res = null
      try {
        res = isUpdate.value ? await modifyContack(param) : await addContack(param)
      } catch (err) {
        console.log('err', err)
      } finally {
        loading.value = false
      }
      if (res?.isSuccess) {
        message.info('仅大陆手机号可接收理赔相关短信内容').then(() => {
          message.success('当前修改已完成，预计次日可查询到。')
        })
        handleCancel()
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}
function handleCancel() {
  phoneEditVisible.value = false
  emit('updateVisible', false)
}
const labelCol = { span: 11 }
</script>
<template>
  <DraggableModal
    v-model:open="phoneEditVisible"
    width="1100px"
    :showSearchPageLink="showSearchPageLink"
    :title="isUpdate ? $t('home.contactModal.EditContact') : $t('home.contactModal.AddContact')"
    @cancel="handleCancel"
  >
    <template #footer>
      <a-button @click="handleCancel">{{ $t('global.cancel') }}</a-button>
      <a-button type="primary" :loading="loading" @click="confirmSave">{{
        $t('global.save')
      }}</a-button>
    </template>
    <a-form ref="formRef" :model="formState" :label-col="labelCol" :rules="rules">
      <a-row :gutter="0">
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Relationship')" name="relationshipWithInsured">
            <a-select
              v-model:value="formState.relationshipWithInsured"
              :allowClear="true"
              show-search
              optionFilterProp="label"
              :options="relationshipList"
              :placeholder="$t('global.PlaceholderSelect')"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Name')" name="contactNameCn">
            <a-input
              v-model:value="formState.contactNameCn"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.EngName')" name="contactNameEn">
            <a-input
              v-model:value="formState.contactNameEn"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Company')" name="company">
            <a-input
              v-model:value="formState.company"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Dept')" name="department">
            <a-input
              v-model:value="formState.department"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Position')" name="position">
            <a-select
              v-model:value="formState.position"
              :allowClear="true"
              show-search
              optionFilterProp="label"
              :options="professionList"
              :placeholder="$t('global.PlaceholderSelect')"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Country')" name="contactCountry">
            <a-select
              v-model:value="formState.contactCountry"
              :allowClear="true"
              :showSearch="true"
              :options="countryList"
              optionFilterProp="dictName"
              :field-names="fieldNames"
              :placeholder="$t('global.PlaceholderSelect')"
              @change="handleCountryChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Prov')" name="contactProvince">
            <a-select
              v-model:value="formState.contactProvince"
              :allowClear="true"
              show-search
              :options="provinceList"
              optionFilterProp="dictName"
              :field-names="fieldNames"
              :placeholder="$t('global.PlaceholderSelect')"
              @change="handleProvinceChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.City')" name="contactCity">
            <a-select
              v-model:value="formState.contactCity"
              :allowClear="true"
              show-search
              optionFilterProp="dictName"
              :options="cityList"
              :field-names="fieldNames"
              :placeholder="$t('global.PlaceholderSelect')"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Note')" name="addRemark">
            <a-input
              v-model:value="formState.addRemark"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.ZIP')" name="zipcode">
            <a-input
              v-model:value="formState.zipcode"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Address')" name="contactAddress">
            <a-input
              v-model:value="formState.contactAddress"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.OfficeTel')" name="officeTel">
            <a-input
              v-model:value="formState.officeTel"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.HomeTel')" name="homeTel">
            <a-input
              v-model:value="formState.homeTel"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Fax')" name="fax">
            <a-input
              v-model:value="formState.fax"
              :allowClear="true"
              :placeholder="$t('global.PlaceholderInput')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.Mobile')">
            <a-input-group compact>
              <a-input
                v-model:value="formState.interCode"
                :placeholder="$t('global.PlaceholderInput')"
                style="width: 30%"
              />
              <a-input
                v-model:value="formState.mobile"
                :placeholder="$t('global.PlaceholderInput')"
                :allowClear="true"
                style="width: 70%"
              />
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label="$t('home.contactModal.AcceptSMS')" name="msgFlag">
            <a-select
              v-model:value="formState.msgFlag"
              :allowClear="true"
              :options="flagList"
              :field-names="fieldNames"
              :placeholder="$t('global.PlaceholderSelect')"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </DraggableModal>
</template>
<style lang="scss"></style>
